#include <sys/epoll.h>
#include "Channel.h"
#include "EventLoop.h"

Channel::Channel(EventLoop *loop, int fd)
{
    this->loop = loop;
    this->fd = fd;
}

void Channel::UseEt()
{
    events |= EPOLLET;
}

void Channel::EnableReading()
{
    events |= EPOLLIN;
    loop->UpdateChannel(this);
}

void Channel::DisableReading()
{
    events &= ~EPOLLIN;
    loop->UpdateChannel(this);
}

void Channel::EnableWriting()
{
    events |= EPOLLOUT;
    loop->UpdateChannel(this);
}

void Channel::DisableWriting()
{
    events &= ~EPOLLOUT;
    loop->UpdateChannel(this);
}

void Channel::DisableAll()
{
    events = 0;
    loop->UpdateChannel(this);
}

void Channel::Remove()
{
    DisableAll();
    loop->RemoveChannel(this);
}

void Channel::HandleEvent() const
{
    if (revents & EPOLLRDHUP) {
        onClose();
    } else if (revents & (EPOLLIN | EPOLLPRI)) {
        onRead();
    } else if (revents & EPOLLOUT) {
        onWrite();
    } else {
        onError();
    }
}